package com.me.netty;

import com.me.config.NettyConfigure;
import com.me.netty.handler.BinaryWebSocketFrameHandler;
import com.me.netty.handler.TextWebSocketFrameHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 通道初始化对象
 */
@Component
public class WebSocketChannelInit extends ChannelInitializer<Channel> {
    @Autowired
    NettyConfigure nettyConfigure;
    @Autowired
    BinaryWebSocketFrameHandler binaryWebSocketFrameHandler;
    @Autowired
    TextWebSocketFrameHandler textWebSocketFrameHandler;

    @Override
    protected void initChannel(Channel ch) {
        ch.pipeline().addLast("logging",new LoggingHandler("DEBUG"));//设置log监听器，并且日志级别为debug，方便观察运行流程
        ch.pipeline().addLast("http-codec",new HttpServerCodec());//设置解码器
        ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());//用于大数据的分区传输
        // HttpObjectAggregator将多个信息转化成单一的request或者response对象
        // post请求三部分 request line / request header/ message body
        ch.pipeline().addLast("aggregator",new HttpObjectAggregator(65536));//聚合器，使用websocket会用到
        ch.pipeline().addLast(new WebSocketServerProtocolHandler(nettyConfigure.getPath()))   ;//自定义的业务handler
        ch.pipeline().addLast(new WebSocketServerCompressionHandler()) ;//自定义的业务handler
        ch.pipeline().addLast(textWebSocketFrameHandler);//自定义的业务handler
        ch.pipeline().addLast(binaryWebSocketFrameHandler);//自定义的业务handler
        ch.pipeline().addLast(new IdleStateHandler(60,0,0, TimeUnit.SECONDS));//自定义的业务handler
    }
}
